import tkinter as tk
from tkinter import ttk, messagebox
import pygetwindow as gw
import pystray
from PIL import Image, ImageDraw
import threading

class App:
    def __init__(self, root):
        self.root = root
        self.root.title("窗口大小调整工具(作者：百倍)")  # 设置窗口标题
        self.root.attributes("-topmost", True)  # 设置窗口总在最前
        self.root.resizable(False, False)  # 禁止窗口最大化
        self.center_window(400, 300)  # 设置窗口大小并居中

        # 创建用户界面组件
        self.create_widgets()
        self.populate_app_list()

        # # 绑定关闭事件
        # self.root.protocol("WM_DELETE_WINDOW", self.minimize_to_tray)

    def center_window(self, width, height):
        # 获取屏幕宽度和高度
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        # 计算窗口位置
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2
        # 设置窗口大小和位置
        self.root.geometry(f"{width}x{height}+{x}+{y}")

    def create_widgets(self):
        # 应用程序选择标签
        self.app_label = tk.Label(self.root, text="选择应用程序:")
        self.app_label.grid(row=0, column=0, padx=10, pady=10, sticky="w")

        # 应用程序下拉框
        self.app_combobox = ttk.Combobox(self.root, state="readonly")
        self.app_combobox.grid(row=0, column=1, columnspan=2, padx=10, pady=10, sticky="ew")
        self.app_combobox.bind("<<ComboboxSelected>>", self.update_window_size)

        # 宽度标签
        self.width_label = tk.Label(self.root, text="自定义宽度(px):")
        self.width_label.grid(row=1, column=0, padx=10, pady=10, sticky="w")

        # 宽度输入框
        self.width_entry = tk.Entry(self.root)
        self.width_entry.grid(row=1, column=1, columnspan=2, padx=10, pady=10, sticky="ew")

        # 高度标签
        self.height_label = tk.Label(self.root, text="自定义高度(px):")
        self.height_label.grid(row=2, column=0, padx=10, pady=10, sticky="w")

        # 高度输入框
        self.height_entry = tk.Entry(self.root)
        self.height_entry.grid(row=2, column=1, columnspan=2, padx=10, pady=10, sticky="ew")

        # 保存按钮
        self.save_button = tk.Button(self.root, text="保存生效", command=self.save_config)
        self.save_button.grid(row=3, column=1, pady=10)

        # 全屏按钮
        self.fullscreen_button = tk.Button(self.root, text="最大化", command=self.fullscreen_app)
        self.fullscreen_button.grid(row=4, column=0, pady=10)

        # 最小化按钮
        self.minimize_button = tk.Button(self.root, text="最小化", command=self.minimize_app)
        self.minimize_button.grid(row=4, column=1, pady=10)

        # 恢复按钮
        self.restore_button = tk.Button(self.root, text="恢复", command=self.restore_app)
        self.restore_button.grid(row=4, column=2, pady=10)

        # 预设尺寸标签
        self.create_size_labels()

        # 使列宽度自适应
        self.root.grid_columnconfigure(1, weight=1)

    def create_size_labels(self):
        # 预设尺寸列表
        sizes = [(1258, 642, "腾讯会议预设"), (800, 600, "预设800x600"), (1024, 768, "预设1024x768"),
                 (1280, 720, "预设1280x720"), (1920, 1080, "预设1920x1080")]
        for i, (width, height, text) in enumerate(sizes):
            # 创建标签
            label = tk.Label(self.root, text=text, fg="blue", cursor="hand2")
            # 设置标签位置
            label.grid(row=5 + i // 3, column=i % 3, padx=10, pady=5)
            # 绑定点击事件
            label.bind("<Button-1>", lambda e, w=width, h=height: self.apply_size(w, h))

    def populate_app_list(self):
        # 获取所有窗口
        windows = gw.getAllWindows()
        # 获取窗口标题、尺寸和进程ID
        app_list = [f"{window.title} ({window.width}*{window.height}) - PID: {window._hWnd}" for window in windows if
                    window.title]
        # 设置下拉框的值
        self.app_combobox['values'] = app_list
        # 默认选择第一个值
        if app_list:
            self.app_combobox.current(0)
            self.update_window_size(None)

    def update_window_size(self, event):
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 更新宽度和高度输入框
            self.width_entry.delete(0, tk.END)
            self.width_entry.insert(0, window.width)
            self.height_entry.delete(0, tk.END)
            self.height_entry.insert(0, window.height)

    def save_config(self):
        # 检查是否选中了一个应用程序
        if not self.app_combobox.get():
            messagebox.showwarning("警告", "请选择一个应用")
            return
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取输入的宽度和高度
        width = self.width_entry.get()
        height = self.height_entry.get()
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 设置窗口大小并激活窗口
            window.resizeTo(int(width), int(height))
            window.activate()
            # 获取屏幕宽度和高度
            screen_width = self.root.winfo_screenwidth()
            screen_height = self.root.winfo_screenheight()
            # 计算窗口位置并移动到中心
            x = (screen_width - int(width)) // 2
            y = (screen_height - int(height)) // 2
            window.moveTo(x, y)

    def apply_size(self, width, height):
        # 检查是否选中了一个应用程序
        if not self.app_combobox.get():
            messagebox.showwarning("警告", "请选择一个应用")
            return
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 设置窗口大小并激活窗口
            window.resizeTo(width, height)
            window.activate()
            # 获取屏幕宽度和高度
            screen_width = self.root.winfo_screenwidth()
            screen_height = self.root.winfo_screenheight()
            # 计算窗口位置并移动到中心
            x = (screen_width - width) // 2
            y = (screen_height - height) // 2
            window.moveTo(x, y)
            # 更新宽度和高度输入框
            self.width_entry.delete(0, tk.END)
            self.width_entry.insert(0, width)
            self.height_entry.delete(0, tk.END)
            self.height_entry.insert(0, height)

    def fullscreen_app(self):
        # 检查是否选中了一个应用程序
        if not self.app_combobox.get():
            messagebox.showwarning("警告", "请选择一个应用")
            return
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 设置窗口全屏
            window.maximize()

    def minimize_app(self):
        # 检查是否选中了一个应用程序
        if not self.app_combobox.get():
            messagebox.showwarning("警告", "请选择一个应用")
            return
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 最小化窗口
            window.minimize()

    def restore_app(self):
        # 检查是否选中了一个应用程序
        if not self.app_combobox.get():
            messagebox.showwarning("警告", "请选择一个应用")
            return
        # 获取选中的窗口标题和进程ID
        selected_item = self.app_combobox.get()
        app_title = selected_item.split(" (")[0]
        hwnd = int(selected_item.split("PID: ")[1])
        # 获取对应的窗口
        windows = [window for window in gw.getAllWindows() if window._hWnd == hwnd]
        if windows:
            window = windows[0]
            # 恢复窗口
            window.restore()

    # def minimize_to_tray(self):
    #     # 创建系统托盘图标
    #     image = Image.new('RGB', (64, 64), color='blue')
    #     draw = ImageDraw.Draw(image)
    #     draw.rectangle((0, 0, 64, 64), fill='blue')
    #     icon = pystray.Icon("FixSize", image, "FixSize", self.create_menu())
    #     # 隐藏主窗口
    #     self.root.withdraw()
    #     # 启动托盘图标
    #     threading.Thread(target=icon.run).start()

    # def create_menu(self):
    #     # 创建托盘菜单
    #     return pystray.Menu(
    #         pystray.MenuItem("显示", self.show_window),
    #         pystray.MenuItem("退出", self.exit_app)
    #     )

    # def show_window(self, icon, item):
    #     # 显示主窗口
    #     self.root.deiconify()
    #     icon.stop()

    # def exit_app(self, icon, item):
    #     # 退出应用程序
    #     icon.stop()
    #     self.root.quit()

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()